// add map area panelId
var dopBtndeliverymanAdd = "";
var dopBtndeliverymanAssign = "";
var mapManager = null;
var isModify = false;
/**
 * 获取根路径basePath
 * @type 
 */
var obj=window.location; 
var contextPath=obj.pathname.split("/")[1]; 
var basePath="";
if(contextPath.indexOf(".do")==-1){
	basePath=obj.protocol+"//"+obj.host+"/"+contextPath; 
}else{
	basePath=obj.protocol+"//"+obj.host;
}
$("#dop_datagrid_deliveryman").datagrid({
	url : "",
	height : 350,
	pagination : true,
	fitColumns : false,
	singleSelect : false,
	fit : true,
	pageSize : 10,
	pageList : [ 10, 30, 50, 100 ],
	sortOrder : 'desc',
	rownumbers : true,
	showFooter : true,
	frozenColumns : [ [] ],
	columns : [ [ {
		field : 'ck',
		checkbox : true
	}, {
		field : "id",
		width : 150,
		title : "主键",
		hidden : true
	}, {
		field : "delName",
		width : 150,
		title : "员工姓名",
		align:'center',
		hidden : true
	}, {
		field : "sUserName",
		width : 150,
		title : "员工姓名",
		align:'center'
	},{
		field : "statusText",
		width : 150,
		title : "接单状态",
		align:'center'
	},  {
		field : "enabledName",
		width : 150,
		title : "启用状态",
		align:'center'
	}, {
		field : "delCertificates",
		width : 150,
		title : "身份证号",
		halign:"center",
		align:'left'
	}, {
		field : "delTelephone",
		width : 150,
		title : "手机",
		halign:"center",
		align:'left'
	},  {
		field : "userId",
		width : 150,
		title : "对应用户",
		hidden : true
	},  {
		field : "areaId",
		width : 150,
		title : "区域ID",
		hidden : true
	}, {
		field : "areaName",
		width : 150,
		title : "区域名称",
		align:'center',
		hidden : true
	},{
		field : "delIntroduction",
		width : 150,
		title : "简介",
		hidden : true
	} ,{
		field : "delPortrait",
		width : 150,
		title : "照片",
		hidden : true
	},{
		field : "userId",
		width : 150,
		title : "用户ID",
		hidden : true
	} ] ]
});

init();

// click pagination
var p = $("#dop_datagrid_deliveryman").datagrid('getPager');
$(p).pagination(
		{
			onSelectPage : function(pageNumber, pageSize) {
				var params = $.extend({
					pageNum : pageNumber,
					pageSize : pageSize
				}, getQueryParams());
				EapTools.doAction("deliveryManController.do?queryList", params,
						false, function(data) {
							$("#dop_datagrid_deliveryman").datagrid('loadData',
									{
										"rows" : data.list,
										"total" : data.count
									} || {});
						});
			}
		});

// bind add event
$("#dop_btn_deliveryman_add")
		.click(
				function() {
					$("#delIntroduction").val("");
					isModify = false;
					$("#delPortraitHide").val("");
					$("#headImg").attr("src",basePath+"/upload/defaultHeadImg.jpg");
					$("#dop_deliveryman_add_panel").find("input").val("");
					dopBtndeliverymanAdd = jQuery
							.layer({
								type : 1,
								title : '<div><span style="padding-left: 14px;line-height: 14px;">添加人员</span></div>',
								shadeClose : true,
								maxmin : false,
								fix : false,
								more:true,
								area : [ 1000, 400 ],
								page : {
									dom : '#dop_deliveryman_add_panel'
								}
							});
				});


// bind modify event
// 关联用户ID，在校验时会用到
var userId = "";
$("#dop_btn_deliveryman_modify").click(
		function() {
			
		
			isModify = true;
			var selections = $("#dop_datagrid_deliveryman").datagrid(
					"getSelections");
			if (selections && selections.length > 0) {
				if (selections.length > 1) {
					layer.tips('请选择一行数据', this, {
						guide : 2,
						time : 2,
						more:true
					});
				} else {
					userId = selections[0].userId;
					oldDelcer=selections[0].delCertificates;
					// 显示地图div
					//$("#dop_btn_deliveryman_add").click();
					// 获得此项记录的坐标字符串
					var delName = selections[0].delName;
					// 更新区域名称的显示
					$("input[id='delName']").attr("disabled",true);
					$("input[id='delName']").val(selections[0].sUserName);
					$("input[id='delCertificates']").val(
							selections[0].delCertificates);
					$("input[id='delTeliPhone']").val(
							selections[0].delTelephone);
					//$("input[id='delMaxmum']").val(selections[0].delMaxmum);
					if(selections[0].delPortrait!=null){
						if(selections[0].delPortrait.length>0){
							$("#headImg").attr("src",basePath+selections[0].delPortrait);
							$("#delPortraitHide").val(selections[0].delPortrait);
						}else{
							$("#headImg").attr("src",basePath+"/upload/defaultHeadImg.jpg");
							$("#delPortraitHide").val("");
						}
					}else{
						$("#headImg").attr("src",basePath+"/upload/defaultHeadImg.jpg");
						$("#delPortraitHide").val("");
					}
					$("input[id='sUser']").val(selections[0].userId);
					$("#delIntroduction").val(selections[0].delIntroduction);
					dopBtndeliverymanAdd = jQuery
					.layer({
						type : 1,
						title : '<div><span style="padding-left: 14px;line-height: 14px;">添加人员</span></div>',
						shadeClose : true,
						maxmin : false,
						fix : false,
						more:true,
						area : [ 1000, 400 ],
						page : {
							dom : '#dop_deliveryman_add_panel'
						}
					});
					
				}
			} else
				layer.tips('请选择要修改行', this, {
					guide : 2,
					time : 2,
					more:true
				});
		});

// bind delete event
$("#dop_btn_deliveryman_delete").click(function() {
	var selections = $("#dop_datagrid_deliveryman").datagrid("getSelections");
	if (selections && selections.length > 0)
		layer.confirm('确定删除吗？', function() {
			EapTools.doAction("deliveryManController.do?delete", {
				"rowList" : JSON.stringify(selections)
			}, false, function(data) {
				if (data.success) {
					EapTip.msgOk("删除成功！");
					init();
				}
			});
		});
	else
		layer.tips('请选择要删除行', this, {
			guide : 2,
			time : 2,
			more:true
		});
});

/**
 * 启用人员
 */
$("#dop_btn_deliveryman_open").click(function(){
	var selections = $("#dop_datagrid_deliveryman").datagrid("getSelections");
	if(selections.length > 0){
		layer.confirm('确定启用吗？', function() {
			var ids=[];
			for(var i=0;i<selections.length;i++){
				ids.push(selections[i].id);
			}
			EapTools.doAction("deliveryManController.do?open", {
				"ids" : ids
			}, true, function(data) {
				if (data.success) {
					EapTip.msgOk("操作成功！");
					init();
				}else{
					EapTip.msgError("操作失败，请重试！");				
				}
			});
			
		});
	}else{
		layer.tips('请选择要启用的行', this, {
			guide : 2,
			time : 2,
			more:true
		});
	}
});
/**
 * 停用人员
 */
$("#dop_btn_deliveryman_stop").click(function(){
	var selections = $("#dop_datagrid_deliveryman").datagrid("getSelections");
	if(selections.length > 0){
		layer.confirm('确定停用吗？', function() {
			var ids=[];
			for(var i=0;i<selections.length;i++){
				ids.push(selections[i].id);
			}
			EapTools.doAction("deliveryManController.do?stop", {
				"ids" : ids
			}, true, function(data) {
				if (data.success) {
					EapTip.msgOk("操作成功！");
					init();
				}else{
					EapTip.msgError("操作失败，请重试！");				
				}
			});
			
		});
	}else{
		layer.tips('请选择要停用的行', this, {
			guide : 2,
			time : 2,
			more:true
		});
	}
});

// bind assign event
$("#dop_btn_deliveryman_assign")
		.click(
				function() {
					var selections = $("#dop_datagrid_deliveryman").datagrid(
							"getSelections");
					if (selections && selections.length > 0) {
						if (selections.length > 1) {
							layer.tips('请选择一行数据', this, {
								guide : 2,
								time : 2,
								more:true
							});
						} else {
							EapTools
									.doAction(
											"areaController.do?findData",
											{},
											false,
											function(data) {
												$("#area").empty();
												for (var i = 0; i < data.length; i++) {
													$("#area")
															.append(
																	"<option value='"
																			+ data[i].id
																			+ "'>"
																			+ data[i].baseAreaName
																			+ "</option>");
													// 为Select追加一个Option(下拉项)
												}
												$("#area").multipleSelect({
													filter : true
												});
											});

							dopBtndeliverymanAssign = jQuery
									.layer({
										type : 1,
										title : '<div><span style="padding-left: 14px;line-height: 14px;">分配区域</span></div>',
										shadeClose : true,
										maxmin : false,
										fix : false,
										more:true,
										area : [ 1000, 250 ],
										page : {
											dom : '#dop_deliveryman_assign_panel'
										}
									});
						}
					} else
						layer.tips('请选择要修改行', this, {
							guide : 2,
							time : 2,
							more:true
						});
				});

// 对sUser进行唯一性验证
// 会员状态，是否已经关联了员工姓名
var sUserFlag = false;
var msg = "";
function sUserChange() {
	var id = $.trim($("#sUser").val());
	if (id.length == 0) {
		sUserFlag = false;
		layerComm("请选择对应用户！","sUser");
	} else if (userId == id) {// 在修改时如果不修改关联用户，只修改其他数据，也会对关联用户进行判断，所以要通过这行跳过验证
		sUserFlag = true;
	} else {
		$.ajax({
			url : "deliveryManController.do?checkUserRelevance",
			cache : false,
			async : false,
			type : "post",
			dataType : "json",
			data : {
				"userId" : id
			},
			success : function(data, textStatus) {
				sUserFlag = data.success;
				if(!data.success){
					layerComm(data.msg,"sUser");
				}
			}
		});
	}
}
//校验证件编号
var delCertificatesFlag = false;
var oldDelcer="";
function chekcDelCertificates(){
	var reg = /^[a-zA-z\d]{0,}$/;
	var val = $.trim($("#delCertificates").val());
	if(val.length==0){
		delCertificatesFlag = false;
		layerComm("编号不得为空!","delCertificates");
		return;
	}
	if(oldDelcer==val){
		delCertificatesFlag = true;
		return ;
	}else if (val.length > 50) {
		delCertificatesFlag = false;
		layerComm("编号不得超过50个字符!","delCertificates");
	} else if (reg.test(val)) {
		//判断证件编号是否已经存在
		EapTools.doAction("deliveryManController.do?chekcDelCertificates",	{"delCertificates":val},
				false,
				function(data) {
					delCertificatesFlag=data.success;
					if(!data.success){
						layerComm("该证件编号已经存在，不能重复添加！","delCertificates");
					}
				});
	} else {
		delCertificatesFlag = false;
		layerComm("编号格式只能为字母和数字!","delCertificates");
	}
}
/**
 * 验证人员电话
 */
var delTeliPhoneFlag=false;
function checkDelTeliPhone(){
	var reg=/^1[3|4|5|8][0-9]\d{8}$/;
	var tel=$.trim($("#delTeliPhone").val());
	if(tel.length==0){
		delTeliPhoneFlag=false;
		layerComm("联系手机号不能为空!","delTeliPhone");
		return;
	}else if(!reg.test(tel)){
		delTeliPhoneFlag=false;
		layerComm("请输入正确格式的手机号!","delTeliPhone");
		return;
	}
	delTeliPhoneFlag=true;
}
/**
 * 验证每日最大送餐量
 */
var delMaxmumFlag=false;
function checkDelMaxmum(){
	var reg=/^[1-9][0-9]{0,4}$/;
	var val=$.trim($("#delMaxmum").val());
	if(val.length==0||val=="0"){
		delMaxmumFlag=true;
		return;
	}else if(!reg.test(val)){
		delMaxmumFlag=false;
		layerComm("数字格式为1~5位!","delMaxmum");
		return;
	}
	delMaxmumFlag=true;
}
/**
 * 图片上传
 */
var imgReg=/(.jpg|.jpeg|.png)$/;
$("#delPortrait").live("change",function(){
	var file=$(this).val();
	if(imgReg.test(file)){
		$.ajaxFileUpload({
			url:"deliveryManController.do?imgUp",
			type:"post",
			secureuri:false,
			fileElementId:"delPortrait",
			dataType:"json",
			//elementIds:["image"],
			success: function(data, status){  
				if(data.success){
					$("#headImg").attr("src",basePath+data.msg);
					$("#delPortraitHide").val(data.msg);
				}else{
					layer.tips(data.msg, document.getElementById("headImg"), {
						guide : 2,
						time : 4,
						more:true
					});
				}
			},
            error: function(data, status, e){ 
                alert("上传失败了，请重试");
            }
		});
	}else{
		layer.tips('请上传jpg、jpeg、png格式的图片', this, {
			guide : 2,
			time : 4,
			more:true
		});
		return false;
	}
});

//校验员工姓名名称
var delNameFlag=false;
function chekcDelName(){
	var val = $.trim($("#delName").val());
	if(val.length==0){
		delNameFlag=false;
		layerComm("员工姓名名称不能为空!","delName");
	}else if (val.length > 50) {
		delNameFlag = false;
		layerComm("员工姓名名称不得超过20个字符!","delName");
	}else{
		delNameFlag=true;
	} 
}
/**
 * 验证人员描述
 */
var delIntroductionFlag=false;
function checkDelIntroduction(){
	var val=$.trim($("#delIntroduction").val());
	if(val.length>200){
		delIntroductionFlag=false;
		layerComm("描述不得超过200个字符!","delIntroduction");
	}else{
		delIntroductionFlag=true;
	}
}
/***
 * layer提示信息封装
 * @param msg  消息内容
 * @param id   要显示位置的元素ID
 */
function layerComm(msg,id){
	layer.tips(msg, document.getElementById(id), {
		guide : 2,
		time : 2,
		more:true
	});
}

/**
 * 绑定keydown事件,只允许输入数字
 */
$("input[code='delMaxmum'],#delTeliPhone").keydown(function(e){
	e = e || event;	
	var code=e.keyCode;
	return (code>36&&code<41)||(code>45&&code<58)||(code>95&&code<107)||code==8||code==9;
});

// 添加面板 确定按钮

$("#dop_deliveryman_add_panel_ok").click(
		function() {
			var delName = $("input[id='delName']").val();
			var delPortraitHide=$("#delPortraitHide").val();
			sUser = $("select[id='sUser']").val();
			//先调用方法进行校验
			//sUserChange();
			chekcDelCertificates();
			//chekcDelName();
			checkDelTeliPhone();
			//checkDelMaxmum();
			checkDelIntroduction();
			if (!(delCertificatesFlag&&delTeliPhoneFlag&&delIntroductionFlag)) {
				layerComm("信息添写不完整，无法提交！","dop_deliveryman_add_panel_ok");
				return;
			}
				if (isModify)
					EapTools.doAction("deliveryManController.do?modify", {
						//delName : $.trim($("input[id='delName']").val()),
						delCertificates : $.trim($("input[id='delCertificates']")
								.val()),
						delIntroduction:$("#delIntroduction").val(),
						delPortrait : delPortraitHide,
						delTeliPhone : $.trim($("input[id='delTeliPhone']").val()),
						//delMaxmum : $.trim($("input[id='delMaxmum']").val()),
						//sUser : $.trim($("select[id='sUser']").val()),
						id : $("#dop_datagrid_deliveryman").datagrid(
								"getSelections")[0].id
					}, false, function(data) {
						layer.close(dopBtndeliverymanAdd);
						EapTip.msgOk("修改成功");
						$("input[id='delName']").val("");
						$("input[id='delCertificates']").val("");
						$("#delIntroduction").val("");
						$("input[id='delTeliPhone']").val("");
						//$("input[id='delMaxmum']").val("");
						$("input[id='sUser']").val("");
						$("#delPortraitHide").val("");
						init();
					});
				else
					EapTools.doAction("deliveryManController.do?create", {
						delName : $.trim($("input[id='delName']").val()),
						delCertificates : $.trim($("input[id='delCertificates']")
								.val()),
						delIntroduction:$("#delIntroduction").val(),
						delPortrait : delPortraitHide,
						delTeliPhone : $.trim($("input[id='delTeliPhone']").val()),
						//delMaxmum : $.trim($("input[id='delMaxmum']").val()),
						sUser : $("select[id='sUser']").val()
					}, false, function(data) {
						layer.close(dopBtndeliverymanAdd);
						EapTip.msgOk("添加成功");
						$("input[id='delName']").val("");
						$("input[id='delCertificates']").val("");
						$("#delIntroduction").val("");
						$("input[id='delTeliPhone']").val("");
						//$("input[id='delMaxmum']").val("");
						$("input[id='sUser']").val("");
						$("#delPortraitHide").val("");
						init();
					});
		});
// 分配面板 确定按钮
$("#dop_deliveryman_assign_panel_ok").click(function() {
	var selectedAreaId = $("#area").val();

	EapTools.doAction("deliveryManController.do?assignArea", {
		id : $("#dop_datagrid_deliveryman").datagrid("getSelections")[0].id,
		areaIdList : selectedAreaId
	}, false, function(data) {
		layer.close(dopBtndeliverymanAssign);
		EapTip.msgOk("分配成功");
		init();
	});

});

// 添加面板 取消按钮
$("#dop_deliveryman_add_panel_cancel").click(function() {
	layer.close(dopBtndeliverymanAdd);
});
// 分配面板 取消按钮
$("#dop_deliveryman_assign_panel_cancel").click(function() {
	layer.close(dopBtndeliverymanAssign);
});

// bind query event
$("#dop_btn_deliveryman_query").click(function() {
	init();
});

/*
// 绑定用户列表
EapTools.doAction("deliveryManController.do?users", {}, false, function(data) {
	var selectorArray = [];
	selectorArray.push("<option value=''>---请选择---</option>");
	for (var i = 0; i < data.length; i++) {
		var thisObj = data[i];
		selectorArray.push("<option value='", thisObj.ID, "'>",
				thisObj.realname, "</option>");
	}
	$("select[id='sUser']").append(selectorArray.join(""));
});
*/
// get params
function getQueryParams() {
	return {
		delName : $("input[code='delName']").val(),
		delCertificates : $("input[code='delCertificates']").val(),
		delTelephone : $("input[code='delTeliPhone']").val()
		//delMaxmum : $("input[code='delMaxmum']").val() || 0
	};
}

// init
function init() {
	// init
	var options = $("#dop_datagrid_deliveryman").datagrid('getPager').data(
			"pagination").options;
	var pageSize = options.pageSize;
	var params = $.extend({
		pageNum : 1,
		pageSize : pageSize
	}, getQueryParams());
	EapTools.doAction("deliveryManController.do?queryList", params, false,
			function(data) {
				$("#dop_datagrid_deliveryman").datagrid('loadData', {
					"rows" : data.list,
					"total" : data.count
				} || {});
				var p = $("#dop_datagrid_deliveryman").datagrid('getPager');
				$("td:last", p).find("a").click();
			});
}
